package com.xxc.hs.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.xxc.hs.R;
import com.xxc.hs.adapter.TraceAdapter;
import com.xxc.hs.bean.TraceInfo;
import com.xxc.hs.db.TraceInfoDAO;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

@SuppressWarnings("ALL")
public class SourceTraceFragment extends Fragment implements TraceAdapter.OnTraceItemClickListener {

    private RequestManager glideRequestManager;
    private EditText searchEdit;
    private Button searchButton, prevPageButton, nextPageButton;
    private TextView pageInfo;
    private RecyclerView traceList;
    private TraceAdapter adapter;
    private TraceInfoDAO traceInfoDAO;

    private String keyword = "";
    private int page = 1;
    private final int PAGE_SIZE = 6;
    private int totalPages = 1;

    public static SourceTraceFragment newInstance() {
        return new SourceTraceFragment();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        glideRequestManager = Glide.with(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_source_trace, container, false);
        initViews(view);
        initData();
        setupListeners();
        return view;
    }

    private void initViews(View view) {
        searchEdit = view.findViewById(R.id.search_edit);
        searchButton = view.findViewById(R.id.search_button);
        prevPageButton = view.findViewById(R.id.prev_page_button);
        nextPageButton = view.findViewById(R.id.next_page_button);
        pageInfo = view.findViewById(R.id.page_info);
        traceList = view.findViewById(R.id.trace_list);

        // 设置RecyclerView（优化缓存）
        traceList.setLayoutManager(new LinearLayoutManager(requireContext()));
        traceList.setItemViewCacheSize(20);              // 增加缓存数量
        traceList.setDrawingCacheEnabled(true);        // 启用绘图缓存
        traceList.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);

        adapter = new TraceAdapter(requireContext(), null, this);
        traceList.setAdapter(adapter);

        traceInfoDAO = new TraceInfoDAO(requireContext());

        // 滚动加载更多
        traceList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                if (layoutManager != null && layoutManager.findLastCompletelyVisibleItemPosition() == adapter.getItemCount() - 1) {
                    if (page < totalPages) {
                        page++;
                        loadTraceInfoList();
                    }
                }
            }
        });
    }

    private void initData() {
        // 加载第一页数据
        loadTraceInfoList();
    }

    private void loadTraceInfoList() {
        showLoading();

        new Thread(() -> {
            List<TraceInfo> traceInfoList = traceInfoDAO.getTraceInfoList(keyword, page, PAGE_SIZE);
            int totalCount = traceInfoDAO.getTotalCount(keyword);
            totalPages = (totalCount + PAGE_SIZE - 1) / PAGE_SIZE;

            // 后台线程预处理数据
            if (traceInfoList != null) {
                for (TraceInfo info : traceInfoList) {
                    // 数据预处理（如路径格式化）
                }
            }

            if (requireActivity() != null && !requireActivity().isDestroyed() && !requireActivity().isFinishing()) {
                requireActivity().runOnUiThread(() -> {
                    hideLoading();
                    adapter.updateData(traceInfoList);
                    updatePagination();
                });
            }
        }).start();
    }

    private void setupListeners() {
        // 搜索按钮点击事件
        searchButton.setOnClickListener(v -> {
            keyword = searchEdit.getText().toString().trim();
            page = 1;
            loadTraceInfoList();
        });

        // 上一页按钮点击事件
        prevPageButton.setOnClickListener(v -> {
            if (page > 1) {
                page--;
                loadTraceInfoList();
            }
        });

        // 下一页按钮点击事件
        nextPageButton.setOnClickListener(v -> {
            if (page < totalPages) {
                page++;
                loadTraceInfoList();
            }
        });
    }

    private void updatePagination() {
        pageInfo.setText("第 " + page + " 页 / 共 " + totalPages + " 页");
        prevPageButton.setEnabled(page > 1);
        nextPageButton.setEnabled(page < totalPages);
    }

    private void showLoading() {
        Toast.makeText(requireContext(), "加载中...", Toast.LENGTH_SHORT).show();
    }

    private void hideLoading() {
        // 可在此处添加加载动画隐藏逻辑
    }

    // 二维码点击事件处理（优化Glide加载）
    @Override
    public void onQrCodeClicked(String qrCode) {
        if (requireActivity() != null && !requireActivity().isDestroyed() && !requireActivity().isFinishing()) {
            View dialogView = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_qr_code, null);
            ImageView qrCodeImage = dialogView.findViewById(R.id.qr_code_image);

            // 加载二维码图片（优化尺寸和缓存）
            int qrCodeResId = requireContext().getResources().getIdentifier(
                    qrCode, "drawable", requireContext().getPackageName());
            Glide.with(this)
                    .load(qrCodeResId)
                    .override(500, 500)       // 设置对话框中二维码尺寸
                    .diskCacheStrategy(DiskCacheStrategy.ALL)  // 缓存策略
                    .error(R.drawable.temp) // 添加错误占位图
                    .into(qrCodeImage);

            new AlertDialog.Builder(requireContext())
                    .setView(dialogView)
                    .setTitle("溯源二维码")
                    .setPositiveButton("关闭", null)
                    .show();
        }
    }

    // 溯源按钮点击事件处理（优化Glide加载）
    @Override
    public void onTraceButtonClicked(TraceInfo traceInfo) {
        if (requireActivity() != null && !requireActivity().isDestroyed() && !requireActivity().isFinishing()) {
            View dialogView = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_trace_detail, null);

            TextView nameText = dialogView.findViewById(R.id.detail_name);
            TextView phoneText = dialogView.findViewById(R.id.detail_phone);
            TextView responsibleText = dialogView.findViewById(R.id.detail_responsible);
            TextView locationText = dialogView.findViewById(R.id.detail_location);
            TextView infoText = dialogView.findViewById(R.id.detail_info);
            ImageView imageView = dialogView.findViewById(R.id.detail_image);

            // 优化图片加载
            int imageResId = requireContext().getResources().getIdentifier(
                    traceInfo.getImagePath(), "drawable", requireContext().getPackageName());
            Glide.with(this)
                    .load(imageResId)
                    .override(800, 600)       // 设置详情图片尺寸
                    .centerCrop()
                    .error(R.drawable.temp) // 添加错误占位图
                    .into(imageView);

            nameText.setText(traceInfo.getName());
            phoneText.setText("联系电话：" + traceInfo.getPhone());
            responsibleText.setText("负责人：" + traceInfo.getResponsible());
            locationText.setText("地点：" + traceInfo.getLocation());
            infoText.setText("溯源信息：" + traceInfo.getTraceInfo());

            new AlertDialog.Builder(requireContext())
                    .setView(dialogView)
                    .setTitle("溯源详情")
                    .setPositiveButton("关闭", null)
                    .show();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        try {
            // 清除RecyclerView引用
            if (traceList != null) {
                traceList.setAdapter(null);
                traceList = null;
            }

            // 清除Glide请求（适配旧版本）
            if (glideRequestManager != null) {
                // 旧版本回退方案
                Glide.get(requireContext()).clearMemory();
            }

            // 移除所有监听器
            searchButton.setOnClickListener(null);
            prevPageButton.setOnClickListener(null);
            nextPageButton.setOnClickListener(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            // 释放数据库资源
            if (traceInfoDAO != null) {
                traceInfoDAO.releaseResources();
                traceInfoDAO = null;
            }

            // 清除适配器数据
            if (adapter != null) {
                adapter.release();
                adapter.updateData(null);
                adapter = null;
            }

            // 置空所有引用
            searchEdit = null;
            searchButton = null;
            prevPageButton = null;
            nextPageButton = null;
            pageInfo = null;
            glideRequestManager = null;

            // 优化：主动释放Glide资源
            if (glideRequestManager != null) {
                Glide.get(requireContext()).clearMemory();
                new Thread(() -> Glide.get(requireContext()).clearDiskCache()).start();

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}